package day4.demo3_信号量;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class Test {
    public static void main(String[] args)throws Exception {
        Semaphore sem = new Semaphore(5);
        for (int i = 0; i < 6; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        sem.acquire();
                        System.out.println(Thread.currentThread().getName()+"占用了车位");
                        TimeUnit.SECONDS.sleep(new Random().nextInt(10));
                        System.out.println(Thread.currentThread().getName()+"离开了车位");
                    } catch (InterruptedException e) {
                    }finally {
                        sem.release();
                    }
                }
            },"线程"+i).start();
        }
    }
}
